import os
import re

import network
import addition

from base import (QAction, QCursor, QFrame, QLabel, QObject, QPixmap, QRunnable, RequestThread,
                  QMenu, QTableWidgetItem, QThreadPool, QueueObject, makeMd5, pyqtSignal)
from netEaseApi import netease
from singsFrameBase import OneSing, PlaylistButton

from asyncBase import aAsync, toTask

from netEaseApi import netease
from apiRequestsBase import HttpRequest

myRequests = HttpRequest()
transTime = addition.itv2time


class ConfigNetEase(QObject):

    def __init__(self, parent=None):
        super(ConfigNetEase, self).__init__()
        self.netEase = parent
        self.netEaseParent = self.netEase.parent
        self.detailFrame = self.netEaseParent.parent.detailSings
        self.mainContents = self.netEaseParent.parent
        self.picThreadPool = QThreadPool()
        self.picThreadPool.setMaxThreadCount(5)
        self.queue = QueueObject()
        self.queue.add.connect(self._setStyleCodesByThreadPool)
        self.netEase.scrollDown.connect(self.sliderDownEvent)
        self.result = []
        self.reqResult = None
        self.cache = None
        self.singsUrls = None
        self.picName = None
        self.singsFrames = []
        self.singPicUrls = []
        self.singNames = []
        self.playlistIds = []
        self.singsIds = []
        self.sliderDown = False
        self.gridRow = 0
        self.gridColumn = 0
        self.offset = 0
        self.offsetComplement = 30
        self.myHeight = 0
        self.api = netease

    def initThread(self):
        self.netThread = RequestThread(self, self.getSings)
        self.netThread.finished.connect(self.threadSetSings)
        self.netThread.setFlag(True)
        self.netThread.start()
        self.singsThread = RequestThread(self)
        self.singsThread.setTarget(self.requestsDetail)
        self.singsThread.finished.connect(self.setRequestsDetail)

    def getSings(self):
        result = self.api.all_playlist(offset=self.offset)
        if not result:
            return

        for i in result:
            self.result.append(i)
            self.singNames.append(i['name'])
            self.singPicUrls.append(i['coverImgUrl'])
            self.playlistIds.append(i['id'])

    def threadSetSings(self):
        if not self.result:
            return
        length = len(self.singPicUrls)

        for i in range(30):
            i += self.offset
            if i >= length:
                self.offsetComplement = length % 30
                break
            picName = makeMd5(self.singPicUrls[i])
            frame = OneSing(self.gridRow, self.gridColumn, self.playlistIds[i], self, picName)
            frame.clicked.connect(self.startRequest)
            frame.nameLabel.setText(self.singNames[i])
            self.netEase.mainLayout.addWidget(frame, self.gridRow, self.gridColumn)
            self.singsFrames.append(frame)

            if self.gridColumn == 3:
                self.gridColumn = 0
                self.gridRow += 1
            else:
                self.gridColumn += 1

            try:
                cacheList = os.listdir('cache')
            except:
                os.mkdir('cache')
                cacheList = os.listdir('cache')

            url = self.singPicUrls[i]

            names = makeMd5(url)
            if names in cacheList:
                frame.setStyleSheets("QLabel#picLabel{border-image: url(cache/%s)}" % (names))
            else:
                task = _PicThreadTask(self.queue, frame, url)
                self.picThreadPool.start(task)
        else:
            self.offsetComplement = 30

    def _setStyleCodesByThreadPool(self):
        data = self.queue.get()
        if not data:
            return
        else:
            data[0].setStyleSheets(data[1])

    def startRequest(self, ids, picName):
        self.picName = picName
        self.singsThread.setArgs(ids)
        self.singsThread.start()

    def requestsDetail(self, ids):
        reqResult = self.api.details_playlist(ids)
        self.reqResult = reqResult
        self.singsIds = [i['id'] for i in reqResult['tracks']]
        self.singsUrls = ['http{0}'.format(i) for i in enumerate(self.singsIds)]

    def setRequestsDetail(self):
        result = self.reqResult
        self.detailFrame.config.setupDetailFrames(result, self.singsUrls, self.singsIds)
        self.detailFrame.picLabel.setSrc('cache/{0}'.format(self.picName))
        self.detailFrame.picLabel.setStyleSheet('''QLabel {padding: 10px;}''')
        self.mainContents.mainContents.setCurrentIndex(1)

    def sliderDownEvent(self):
        if self.netEase.isHidden() == False:
            self.offset += self.offsetComplement
            if self.netThread.isRunning():
                return
            else:
                self.netThread.start()


class _PicThreadTask(QRunnable):
    # finished = pyqtSignal(QFrame, str)
    def __init__(self, queue, widget=None, url=None):
        super(_PicThreadTask, self).__init__()
        self.queue = queue
        self.widget = widget
        self.url = url

    def run(self):
        names = makeMd5(self.url)
        content = network.Requests.get(self.url).content
        pic = QPixmap()
        pic.loadFromData(content)
        pic = pic.scaled(180, 180)
        a = pic.save("cache/{0}".format(names), 'jpg')
        self.queue.put([self.widget, "QLabel#picLabel{border-image: url(cache/%s)}" % (names)])
